//
//  ST_CommentListViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh
import SwiftyUserDefaults


class ST_CommentListViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title_nav_btn.setTitleForAllStates("评论")
        
         
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        
        view.addSubview(bottom_input_action_view)
        bottom_input_action_view.snp.makeConstraints { (make) in
            make.height.equalTo(ST_PecGroupBottomView.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        view.addSubview(comment_input_mask_view)
        comment_input_mask_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(comment_input_bar)
        comment_input_bar.snp.makeConstraints { (make) in
            make.height.equalTo(ST_CommentInputBar.height)
            make.bottom.left.right.equalToSuperview()
        }
        
        request_data()
        
    }
    
    
//    MARK: - Request Data
    var groupId = 0
    
    var userId = ""
    
    var peculiarity_id = ""
//    统计使用
    var featureName = ""
    /*1文字 2 表情*/
    var type = 1{
        didSet{
            self.comment_input_bar.onlyInputEmoji = type == 2
        }
    }
    
    fileprivate var currentPage = 0
    
    fileprivate var data_array = [ST_CommentTableCellModel]()
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        JVrequest(PH.queryPecCommentsApi,parameters: ["page":self.currentPage,"size":20,"group_id":groupId], success: { (json) in
            
            let data = json["data"]
            
            var count = 0
            
            if let list = [ST_CommentTableCellModel].deserialize(from: data["list"].rawString() ?? "") as? [ST_CommentTableCellModel]{
                
                list.forEach{
                    $0.ownUserId = self.userId
                    $0.setUpDataSet()
                }
                
                count = list.count
                
                if self.currentPage == 1{
                    self.data_array = list
                }else{
                    self.data_array += list
                }
                
            }
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
            
            self.tableView.reloadData {
                
                self.load_more_option_style(tableView: self.tableView, count: count, pageSize: 20) {
                    
                    self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
            }
            
            self.hidden_indeterminate_h_u_d()
            
            
        }) { (code, err) in
            
            
            self.toast(text: err)
            
            self.tableView.mj_footer?.endRefreshing()
            self.tableView.mj_header?.endRefreshing()
        }
        
        
    }

//    MARK: - Properties
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView()
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 100 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.register(cellWithClass: UITableViewCell.self)
        control.register(cellWithClass: ST_CommentTableCell.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        return control
    }()
    
    fileprivate lazy var bottom_input_action_view:ST_PecGroupBottomView = {
       let control = ST_PecGroupBottomView()
        control.beginInput = {[weak self] in
            self?.comment_input_bar.startEdit()
        }
        return control
    }()
    
    
    fileprivate lazy var comment_input_bar:ST_CommentInputBar = {
       let control = ST_CommentInputBar()
        control.endEditClosure = {[weak self] str,replyId,commentId in
            
            self?.end_edit_comment_handle()
            
            self?.send_message_handle(comment: str, replyUserId: replyId, commentId: commentId)
        }
        control.keyBroadHiddenClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: true)
        }
        control.keyBroadShowClosure = {[weak self]  in
            self?.hidden_mask_view(hidden: false)
        }
        
        if FACE_AVATAE_STATE != 3{
            control.onlyInputEmoji = true
        }
        return control
    }()
    
    fileprivate lazy var comment_input_mask_view:UIView = {
       let control = UIView()
        control.alpha = 0
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(end_edit_comment_handle))
        control.addGestureRecognizer(tap)
        return control
    }()
}

//MARK: - Event
extension ST_CommentListViewController{
    
    @objc fileprivate func end_edit_comment_handle(){
        
        comment_input_bar.endEditing(true)
        
        
    }
    
    func hidden_mask_view(hidden:Bool){

        UIView.animate(withDuration: 0.25, animations: {
            
            self.comment_input_mask_view.alpha = hidden ? 0 : 1
            
        }) { (f) in
            
        }
        
    }
    
    func send_message_handle(comment:String,replyUserId:String?,commentId:String?){
        
        //        只能发表情，但是没有检测到表情
        if self.type == 2 && comment.containEmoji == false{
            
            self.toast(text: "该特质只支持emoji评论")
            
            return
        }
        
        var param = ["target_accid":self.userId,"feature_id":self.peculiarity_id,"group_id":self.groupId,"type":self.type,"comment":comment] as [String : Any]
        
        if let id = commentId{
            param.updateValue(id, forKey: "target_comment_id")
        }
        if let id = replyUserId{
            param.updateValue(id, forKey: "target_member_id")
          
        //            收到的评论页｜个人特质页
                    
            ST_BTGlobalDataCenter.shared.reply_peculiarity_comment_event(peculiarity_id: self.groupId.string, reply_user_id: id,source: "个人特质页", is_own_peculiarity: self.userId == Defaults[.currentUserID])
            
        }else{
            
            ST_BTGlobalDataCenter.shared.commentPeculiarityEvent(peculiarity_id: self.groupId.string, commented_user_id: self.userId)
            
        }
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
                    return
                }
        
        if restrictFemaleFace(){
            return
        }
        
        if ST_BTUserInfoManager.shared.confined_to_ticket(){
                
                let vc = ST_TicketViewController()
                
                vc.from = .mainIndexConfined
                
                GlobalPresent(toController: vc)
                
                return
            }
        
        JVrequest(PH.sendCommentApi,parameters: param, success: { (json) in
            
            self.currentPage = 0
            
            self.request_data()
            
        }) { (code, err) in
            self.toast(text: err)
        }
        
    }
    
    
}
//MARK: - UITableViewDelegate
extension ST_CommentListViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_CommentTableCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return data_array[indexPath.row].cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let m = data_array[indexPath.row]
        
        let nickname = m.nickname
        
        
        self.comment_input_bar.startEdit(replyUserId: m.id.string, commentId: m.comment_id.string, nickName: nickname)
        
    }
    
    
}
